using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Sensor.UI.Models;

namespace Sensor.UI.ViewModels;

/// <summary>
/// 主ViewModel，协调串口、日志和渲染三个ViewModel
/// </summary>
public partial class MainViewModel : ViewModelBase, IDisposable
{
    [ObservableProperty]
    private SerialConfigViewModel _serialConfig;

    // 三个子ViewModel
    [ObservableProperty]
    private SerialPortViewModel _serialPortViewModel;

    [ObservableProperty]
    private LogViewModel _logViewModel;

    [ObservableProperty]
    private RenderViewModel _renderViewModel;

    // 当前会话状态
    [ObservableProperty]
    private bool _isSessionActive = false;

    [ObservableProperty]
    private string _statusMessage = "就绪";

    public MainViewModel()
    {
        // 初始化串口配置
        SerialConfig = new SerialConfigViewModel();

        // 初始化三个子ViewModel
        SerialPortViewModel = new SerialPortViewModel();
        LogViewModel = new LogViewModel();
        RenderViewModel = new RenderViewModel();

        // 设置默认串口
        if (SerialConfig.Port.Count > 0)
        {
            SerialPortViewModel.Port = SerialConfig.Port[0];
        }

        // 订阅串口ViewModel的事件
        SerialPortViewModel.DataReceived += OnDataReceived;
        SerialPortViewModel.MessageReceived += OnMessageReceived;
        SerialPortViewModel.SensorDataReceived += OnSensorDataReceived;
        SerialPortViewModel.ExceptionOccurred += OnExceptionOccurred;
        SerialPortViewModel.IsOpenChanged += OnSerialPortOpenChanged;

        // 添加初始日志
        LogViewModel.AddInfo("应用程序已启动");
        StatusMessage = "就绪";
    }

    /// <summary>
    /// 串口打开/关闭状态变化处理
    /// </summary>
    private void OnSerialPortOpenChanged(object? sender, bool isOpen)
    {
        IsSessionActive = isOpen;
        StatusMessage = isOpen ? "串口已连接" : "串口已断开";
        LogViewModel.AddInfo(isOpen ? "串口连接已建立" : "串口连接已断开");
    }

    /// <summary>
    /// 数据接收事件处理
    /// </summary>
    private void OnDataReceived(object? sender, byte[] data)
    {
        // 可以在这里处理原始字节数据
        // 例如：记录数据统计信息
        LogViewModel.AddDebug($"接收到 {data.Length} 字节数据");
    }

    /// <summary>
    /// 消息接收事件处理
    /// </summary>
    private void OnMessageReceived(object? sender, string message)
    {
        // 将消息传递给日志ViewModel
        LogViewModel.ProcessSerialMessage(message);
    }

    /// <summary>
    /// 传感器数据接收事件处理
    /// </summary>
    private void OnSensorDataReceived(object? sender, SensorInfo sensorInfo)
    {
        // 将传感器数据传递给渲染ViewModel
        RenderViewModel.AddSensorData(sensorInfo);
        
        // 记录日志
        LogViewModel.AddInfo($"接收到传感器数据: X={sensorInfo.X}, Y={sensorInfo.Y}, Z={sensorInfo.Z}, Value={sensorInfo.Value}");
    }

    /// <summary>
    /// 异常事件处理
    /// </summary>
    private void OnExceptionOccurred(object? sender, Exception ex)
    {
        // 将异常传递给日志ViewModel
        LogViewModel.ProcessException(ex);
        StatusMessage = $"错误: {ex.Message}";
    }

    /// <summary>
    /// 打开/关闭串口命令
    /// </summary>
    [RelayCommand]
    private async Task PortAsync()
    {
        try
        {
            if (!SerialPortViewModel.IsOpen)
            {
                StatusMessage = "正在连接串口...";
                LogViewModel.AddInfo($"正在尝试连接串口: {SerialPortViewModel.Port}");
                
                bool success = await SerialPortViewModel.OpenAsync();
                if (!success)
                {
                    StatusMessage = "串口连接失败";
                    LogViewModel.AddError("无法打开串口，请检查配置");
                }
            }
            else
            {
                StatusMessage = "正在断开串口...";
                LogViewModel.AddInfo("正在断开串口连接");
                
                await SerialPortViewModel.CloseAsync();
            }
        }
        catch (Exception ex)
        {
            LogViewModel.ProcessException(ex);
            StatusMessage = $"操作失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 清空数据命令
    /// </summary>
    [RelayCommand]
    private void ClearData()
    {
        // 清空日志
        LogViewModel.ClearLogs();
        
        // 清空渲染数据
        RenderViewModel.ClearPointCloud();
        
        LogViewModel.AddInfo("已清空所有数据");
        StatusMessage = "数据已清空";
    }

    /// <summary>
    /// 重置视图命令
    /// </summary>
    [RelayCommand]
    private void ResetView()
    {
        // 重置渲染视图
        RenderViewModel.ResetView();
        
        LogViewModel.AddInfo("视图已重置");
        StatusMessage = "视图已重置";
    }

    /// <summary>
    /// 打开仓库链接命令
    /// </summary>
    [RelayCommand]
    private static void OpenRepoLink()
    {
        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
        {
            FileName = "https://github.com/cr0vL3Y/WPF.ComTool",
            UseShellExecute = true
        });
    }

    /// <summary>
    /// 窗口最小化命令
    /// </summary>
    [RelayCommand]
    private static void WindowMinimize(object parameter)
    {
        if (parameter is Window window)
        {
            window.WindowState = WindowState.Minimized;
        }
    }

    /// <summary>
    /// 窗口关闭命令
    /// </summary>
    [RelayCommand]
    private static void WindowClose(object parameter)
    {
        if (parameter is Window window)
        {
            window.Close();
        }
    }

    #region 资源释放
    private bool _disposedValue = false;

    /// <summary>
    /// 释放资源
    /// </summary>
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposedValue)
        {
            if (disposing)
            {
                // 取消事件订阅
                if (SerialPortViewModel != null)
                {
                    SerialPortViewModel.DataReceived -= OnDataReceived;
                    SerialPortViewModel.MessageReceived -= OnMessageReceived;
                    SerialPortViewModel.SensorDataReceived -= OnSensorDataReceived;
                    SerialPortViewModel.ExceptionOccurred -= OnExceptionOccurred;
                    SerialPortViewModel.IsOpenChanged -= OnSerialPortOpenChanged;
                }

                // 释放子ViewModel
                SerialPortViewModel?.Dispose();
                RenderViewModel?.Dispose();
                
                // LogViewModel不需要特殊释放
            }

            _disposedValue = true;
        }
    }

    /// <summary>
    /// 析构函数
    /// </summary>
    ~MainViewModel()
    {
        Dispose(false);
    }

    /// <summary>
    /// 实现IDisposable接口
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion
}
